#include "RingQueue.hpp"
#include "Thread.hpp"
#include <vector>
#include <unistd.h>
#include <ctime>
#include"Task.hpp"
using namespace ThreadModule;
using ringqueue_t = RingQueue<Task>;

void PrintHello()
{
    std::cout<<"hello world"<<std::endl;
}
void Consumer(ringqueue_t &rq,const std::string threadname)
{
    while (1)
    {
        sleep(1);
        Task t;
        rq.Pop(&t);
        
        // std::cout << "Consumer... data: "<< data <<  "  --[name: " <<threadname<<"]" <<std::endl;
        std::cout<<"Consumer handle task" <<"[name: "<<threadname<<"]" <<std::endl;
        t();
    }
}
void Productor(ringqueue_t &rq, const std::string threadname)
{

    srand(time(nullptr) ^ pthread_self());
    int cnt = 1;
    while (1)
    {
        // sleep(1);
        rq.Enqueue(DownLoad);
        std::cout << "Productor... data: "<< cnt <<  "--[name: " <<threadname<<"]" <<std::endl;
        
        cnt++;
    }

}
void InitCommon(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq, func_t<ringqueue_t> func)
{
    int a = 10;
    for (int i = 0; i < num; i++)
    {
        std::string name = "thread-" + std::to_string(i + 1);
        threads->emplace_back(func, rq, name);
    }
}

void InitConsumer(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitCommon(threads, num, rq, Consumer);
}

void InitProductor(std::vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitCommon(threads, num, rq, Productor);
}
void StartAll(std::vector<Thread<ringqueue_t>>& threads)
{
    for(auto& thread: threads){
        std::cout<<"start: " <<thread.name()<<std::endl;
        thread.Start();
    }
}
void WaitAllThread(std::vector<Thread<ringqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}

int main()
{
    ringqueue_t *rq = new ringqueue_t(10);
    std::vector<Thread<ringqueue_t>> threads;
    InitConsumer(&threads, 1, *rq);
    InitProductor(&threads, 1, *rq);

    StartAll(threads);
    WaitAllThread(threads);
}